# 第一步：用poplib把邮件的原始文本下载到本地；第二步：用email解析原始文本，还原为邮件对象。
import poplib
from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr
email_addr = "q1750900216@aliyun.com"
password = "123654788m"
pop3_server = "pop3.aliyun.com"
# -------------------连接pop3-------------------------------------------------------------------------------------------
server = poplib.POP3(pop3_server)  # 连接到POP3服务器
server.set_debuglevel(1)  # 可以打开或关闭调试信息
print(server.getwelcome().decode("utf-8"))  # 可选:打印POP3服务器的欢迎文字
# ----身份认证-------
server.user(email_addr)
server.pass_(password)
print("MessageNum:%s Size:%s" % server.stat())  # stat()返回邮件数量和占用空间
resp, mails, octets = server.list()  # list()返回所有邮件的编号
index = len(mails)
resp, lines, octets = server.retr(index)
# lines存储了邮件的原始文本的每一行,可以获得整个邮件的原始文本
msg_content = b'\r\n'.join(lines).decode('utf-8')
# ------------------解析邮件--------------------------------------------------------------------------------------------
msg = Parser().parsestr(msg_content)  # Message对象本身可能是一个MIMEMultipart对象，即包含嵌套的其他MIMEBase对象。


def decode_str(s):
    value, charset = decode_header(s)[0]
    if charset:
        value = value.decode(charset)
    return value


def guess_charset(message):
    charset = message.get_charset()
    if charset is None:
        content_type = message.get("Content-Type", "").lower()
        pos = content_type.find("charset=")
        if pos >= 0:
            charset = content_type[pos + 8:].strip()
    return charset


def print_info(message, indent=0):
    if indent == 0:
        for header in ["Form", "To", "Subject"]:
            value = message.get(header, "")
            if value:
                if header == "Subject":
                    value = decode_str(value)
                else:
                    hdr, addr = parseaddr(value)
                    name = decode_str(hdr)
                    value = u"%s <%s>" % (name, addr)
            print("%s %s: %s" % ("   " * indent, header, value))
    if message.is_multipart():
        parts = message.get_payload()
        for n, part in enumerate(parts):
            print('%s part %s' % ('  ' * indent, n))
            print('%s--------------------' % ('  ' * indent))
            print_info(part, indent + 1)
    else:
        content_type = message.get_content_type()
        if content_type == "text/plain" or content_type == "text/html":
            content = message.get_payload(decode=True)
            charset = guess_charset(message)
            if charset:
                content = content.decode(charset)
                print('%sText: %s' % ('  ' * indent, content + '...'))
            else:
                print('%sAttachment: %s' % ('  ' * indent, content_type))


# server.dele(index)  # 可以根据邮件索引号直接从服务器删除邮件
print_info(msg)
server.quit()  # 关闭连接
